<?php
/**
 *+------------------
 * madong
 *+------------------
 * Copyright (c) https://gitee.com/motion-code  All rights reserved.
 *+------------------
 * Author: Mr. April (405784684@qq.com)
 *+------------------
 * Official Website: http://www.madong.tech
 */

namespace madong\laravel\wf\dao;

use madong\laravel\wf\basic\BaseDao;
use madong\ingenious\libs\utils\ArrayHelper;
use madong\laravel\wf\model\ProcessTaskActor;

class ProcessTaskActorDao extends BaseDao
{

    protected function setModel(): string
    {
        return ProcessTaskActor::class;
    }

    public function getList($where = [], $field = ['*'], $page = 0, $limit = 0, $order = '', $with = []): array
    {
        $amap = ArrayHelper::filterArray(ArrayHelper::paramsFilter($where, [
            ['actor_id'],
        ]));
        $tmap = ArrayHelper::filterArray(ArrayHelper::paramsFilter($where, [
            ['task_name', '', '', 'name'],
            ['task_state'],
            ['perform_type'],
            ['task_display_name', '', '', 'display_name'],
            ['operator'],
        ]));
        $imap = ArrayHelper::filterArray(ArrayHelper::paramsFilter($where, [
            ['business_no'],
            ['instance_name', '', '', 'name'],
            ['instance_display_name', '', '', 'display_name'],
        ]));

        $dmap = ArrayHelper::filterArray(ArrayHelper::paramsFilter($where, [
            ['process_name', '', '', 'name'],
            ['process_display_name', '', '', 'display_name'],
        ]));

        $query = $this->getModel()->with(['task', 'instance.define'])
            ->where($amap)
            ->whereHas('task', function ($query) use ($tmap) {
                if (!empty($tmap)) {
                    $query->where($tmap);
                }
            })
            ->whereHas('instance', function ($query) use ($imap, $dmap) {
                if (!empty($imap)) {
                    $query->where($imap);
                }
                // 将 $dmap 的条件放入 define 的子闭包中
                $query->whereHas('define', function ($query) use ($dmap) {
                    if (!empty($dmap)) {
                        $query->where($dmap);
                    }
                });
            })
            ->orderBy('create_time', 'desc')
            ->paginate($limit, ['*'], 'page', $page);
        return [
            $query->items(),
            $query->total(),
        ];
    }
}
